package io.renren.modules.app.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.R;
import io.renren.modules.PCguanli.dao.LineDao;
import io.renren.modules.PCguanli.dao.LineDeptDao;
import io.renren.modules.PCguanli.entity.LineDeptEntity;
import io.renren.modules.PCguanli.entity.LineEntity;
import io.renren.modules.app.dao.LinedptDao;
import io.renren.modules.app.dao.UserDao;
import io.renren.modules.app.dao.UserRegistrationDao;
import io.renren.modules.app.entity.Response;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.entity.UserRegistrationEntity;
import io.renren.modules.app.service.LinedeptService;
import io.renren.modules.app.service.WechatTokenService;
import io.renren.modules.app.wx.WeChatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/app/line")
public class UserLineApiController {

    @Autowired
    private LineDao lineDao;
    @Autowired
    private LinedeptService linedeptService;
    @Autowired
    private UserRegistrationDao userRegistrationDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private LineDeptDao lineDeptDao;
    @Autowired
    private WechatTokenService wechatTokenService;

    /**
     * 报道处理列表
     *
     * @param purchaseplant
     * @return
     */
    @GetMapping("/list")//驻厂人员报道处理列表，三个厂不同车型一起排队，其他厂不同车型分别排队
    public Response list(String purchaseplant,int lineOrder) {
        String startOfToday = DateUtil.beginOfDay(DateUtil.date()).toString();
        String startOfTomorrow = DateUtil.beginOfDay(DateUtil.tomorrow()).toString();

        LineDeptEntity lineDeptEntity = lineDeptDao.selectOne(new LambdaQueryWrapper<LineDeptEntity>()
                        .eq(LineDeptEntity::getDeptName,purchaseplant));
        //有3个厂不按车型排队
        if(purchaseplant.equals("ABS") ||purchaseplant.equals("PS")||purchaseplant.equals("SAP")){
            List<LineEntity> lineEntities = lineDao.selectList(new LambdaQueryWrapper<LineEntity>()
                    .eq(LineEntity::getDeptId, lineDeptEntity.getDeptId())
                    .ge(LineEntity::getRegistertime, startOfToday)
                    .lt(LineEntity::getRegistertime, startOfTomorrow)
                    .in(LineEntity::getRegisterstate, "1", "2", "3", "4")
                    //报道状态升序 1已叫号   2.
                    .orderByAsc(LineEntity::getRegisterstate)
                    //急单（是1否0） 倒叙  急单在前
                    .orderByDesc(LineEntity::getUrgency)
                    //根据时间倒叙
                    .orderByAsc(LineEntity::getRegistertime));

            if (lineEntities.isEmpty()) {
                return new Response(404, "该厂该车型暂无人员排队", null);
            }
            List<Map<String, Object>> InfoList = new ArrayList<>();
            //遍历所有订单，处理排队信息
            for (LineEntity entity : lineEntities) {
                Map<String, Object> Info = getInfo(entity.getIdcard(),entity.getRegistertime());
                InfoList.add(Info);
            }
            return new Response(0, "Success", InfoList);
        }
        //其他的按车型lineOrder排队
        else{
            List<LineEntity> lineEntities = lineDao.selectList(new LambdaQueryWrapper<LineEntity>()
                    .eq(LineEntity::getLineorder,lineOrder)
                    .eq(LineEntity::getDeptId, lineDeptEntity.getDeptId())
                    .ge(LineEntity::getRegistertime, startOfToday)
                    .lt(LineEntity::getRegistertime, startOfTomorrow)
                    .in(LineEntity::getRegisterstate, "1", "2", "3", "4")
                    //报道状态升序 1已叫号   2.
                    .orderByAsc(LineEntity::getRegisterstate)
                    //急单（是1否0） 倒叙  急单在前
                    .orderByDesc(LineEntity::getUrgency)
                    //根据时间倒叙
                    .orderByAsc(LineEntity::getRegistertime));

            if (lineEntities.isEmpty()) {
                return new Response(404, "该厂该车型暂无人员排队", null);
            }
            List<Map<String, Object>> InfoList = new ArrayList<>();
            //遍历所有订单，处理排队信息
            for (LineEntity entity : lineEntities) {
                Map<String, Object> Info = getInfo(entity.getIdcard(),entity.getRegistertime());
                InfoList.add(Info);
            }
            return new Response(0, "Success", InfoList);
        }
        }

    private Map<String, Object> getInfo(String id, String time) {
        Map<String, Object> map = new HashMap<>();
        UserEntity user = userDao.findByID(id);
        UserRegistrationEntity userRegistrationEntity =userRegistrationDao.selectOne(new LambdaQueryWrapper<UserRegistrationEntity>()
                .eq(UserRegistrationEntity::getDriverid,user.getUser_id())
                .eq(UserRegistrationEntity::getTime,time));
        LineEntity lineEntity =lineDao.selectOne(new LambdaQueryWrapper<LineEntity>().eq(LineEntity::getRegistertime,time)
                .eq(LineEntity::getIdcard,id));
        //司机
        map.put("recordid", userRegistrationEntity.getRecordid());
        map.put("carnumber",userRegistrationEntity.getCarnumber());
        map.put("way",userRegistrationEntity.getWay());
        map.put("iphone",user.getIPhone());
        map.put("numberre", lineEntity.getNumberre());
        map.put("deptId", lineEntity.getDeptId());
        map.put("carshop", lineEntity.getCarshop());
        map.put("idrp", lineEntity.getIdrp());
        map.put("userid",user.getUser_id());
        map.put("idcard", lineEntity.getIdcard());
        map.put("lineorder", lineEntity.getLineorder());
        map.put("urgency", lineEntity.getUrgency());
        map.put("registertime", lineEntity.getRegistertime());
        map.put("registerstate", lineEntity.getRegisterstate());
        return map;
        }


    @GetMapping("/oldorderlist")//历史订单
    public Response oldorderlist(@RequestParam int userId) {
        String startOfToday = DateUtil.beginOfDay(DateUtil.date()).toString();
        List<UserRegistrationEntity> userRegistrationEntityList = userRegistrationDao.selectList(new LambdaQueryWrapper<UserRegistrationEntity>()
                .eq(UserRegistrationEntity::getDriverid, userId)
                .lt(UserRegistrationEntity::getTime, startOfToday)
                //根据时间倒叙
                .orderByAsc(UserRegistrationEntity::getTime));

        if (userRegistrationEntityList.isEmpty()) {
            return new Response(404, "暂无订单", null);
        }
        List<Map<String, Object>> oldLists = new ArrayList<>();
        //遍历所有订单，处理排队信息
        for (UserRegistrationEntity entity : userRegistrationEntityList) {
            Map<String, Object> Info = Info(entity.getDatcherid(),entity.getDriverid(),entity.getRecordid());
            oldLists.add(Info);
        }
        return new Response(0, "Success", oldLists);

    }
    private Map<String, Object> Info(Integer datcherid,int userId, int recordId) {
        Map<String, Object> map = new HashMap<>();
        if (datcherid == null) {
            map.put("datcher", "助手未绑定");
        } else {
            UserEntity datcher = userDao.findByUserId(datcherid);
            //押运人员
            map.put("datcher", datcher.getName());
        }
        UserRegistrationEntity userRegistrationEntity = userRegistrationDao.selectOne(new LambdaQueryWrapper<UserRegistrationEntity>()
                .eq(UserRegistrationEntity::getRecordid,recordId));
        UserEntity user =userDao.findByUserId(userRegistrationEntity.getDriverid());
        //司机
        map.put("recordid", userRegistrationEntity.getRecordid());
        map.put("purchaseplant", userRegistrationEntity.getPurchaseplant());
        map.put("carshop", userRegistrationEntity.getCarshop());
        map.put("way", userRegistrationEntity.getWay());
        map.put("model", userRegistrationEntity.getModel());
        map.put("driver", user.getName());
        map.put("carnumber", userRegistrationEntity.getCarnumber());
        map.put("carrythings", userRegistrationEntity.getCarrythings());
        map.put("ordernumber", userRegistrationEntity.getOrderNumber());
        map.put("tonnage", userRegistrationEntity.getTonnage());
        map.put("registertime", userRegistrationEntity.getTime());
        map.put("registerstate", userRegistrationEntity.getState());
        return map;
    }

    @GetMapping("/noworderlist")//今日订单
    public Response noworderlist(@RequestParam int userId) {
        String startOfToday = DateUtil.beginOfDay(DateUtil.date()).toString();
        String startOfTomorrow = DateUtil.beginOfDay(DateUtil.tomorrow()).toString();
        //今日所有订单记录
        List<UserRegistrationEntity> userRegistrationEntityList = userRegistrationDao.selectList(new LambdaQueryWrapper<UserRegistrationEntity>()
                .eq(UserRegistrationEntity::getDriverid, userId)
                .ge(UserRegistrationEntity::getTime, startOfToday)
                .lt(UserRegistrationEntity::getTime, startOfTomorrow)
                .in(UserRegistrationEntity::getState, "1", "2", "3", "4","5","6","7")
                //报道状态升序 1已叫号   2.
                .orderByAsc(UserRegistrationEntity::getState)
                //根据时间倒叙
                .orderByAsc(UserRegistrationEntity::getTime));

        if (userRegistrationEntityList.isEmpty()) {
            return new Response(404, "暂无订单", null);
        }

        List<Map<String, Object>> orderInfoList = new ArrayList<>();
        //遍历所有订单，处理排队信息
        for (UserRegistrationEntity entity : userRegistrationEntityList) {
            Map<String, Object> orderInfo = getOrderInfo(userId, entity.getPurchaseplant(), entity.getRecordid());
            orderInfoList.add(orderInfo);
        }

        return new Response(0, "Success", orderInfoList);
    }

    private Map<String, Object> getOrderInfo(int userId, String purchaseplant, int recordId) {
        Map<String, Object> map = new HashMap<>();
        UserEntity userEntity = userDao.findByUserId(userId);

        LineDeptEntity lineDeptEntity = lineDeptDao.selectOne(new LambdaQueryWrapper<LineDeptEntity>().eq(LineDeptEntity::getDeptName, purchaseplant));
        //司机
        map.put("driver", userEntity.getName());
        UserRegistrationEntity userRegistrationEntity = userRegistrationDao.selectOne(new LambdaQueryWrapper<UserRegistrationEntity>()
                .eq(UserRegistrationEntity::getRecordid, recordId));
        map.put("ordernumber", userRegistrationEntity.getOrderNumber());
        Integer datcherid = userRegistrationEntity.getDatcherid();
        if (datcherid == null) {
            map.put("datcher", "助手未绑定");
        } else {
            UserEntity datcher = userDao.findByUserId(datcherid);
            //押运人员
            map.put("datcher", datcher.getName());
        }
        map.put("recordid", userRegistrationEntity.getRecordid());
        //车牌号
        map.put("carnumber", userRegistrationEntity.getCarnumber());
        //当前排队车数,用户当天在排队表里的数量，状态2
        map.put("state", userRegistrationEntity.getState()); //状态
        String startOfToday = DateUtil.beginOfDay(DateUtil.date()).toString();
        String startOfTomorrow = DateUtil.beginOfDay(DateUtil.tomorrow()).toString();
        int lineOrder = 0;
        if (userRegistrationEntity.getModel().equals("平板P")) {
            lineOrder = 1;
        } else if (userRegistrationEntity.getModel().equals("厢式X")) {
            lineOrder = 2;
        }
        if (purchaseplant.equals("ABS") || purchaseplant.equals("PS") || purchaseplant.equals("SAP")) {
            //这三个厂不同车型一起排队，给今天该厂状态为2的排序
            List<LineEntity> lineEntities = lineDao.selectList(new LambdaQueryWrapper<LineEntity>()
                    .ge(LineEntity::getRegistertime, startOfToday)
                    .lt(LineEntity::getRegistertime, startOfTomorrow)
                    .eq(LineEntity::getDeptId, lineDeptEntity.getDeptId())
                    .eq(LineEntity::getRegisterstate, 2)
                    .orderByAsc(LineEntity::getRegisterstate)
                    .orderByAsc(LineEntity::getRegistertime)
            );
            //找到该用户的排队资料
            LineEntity lineEntity = lineDao.selectOne(new LambdaQueryWrapper<LineEntity>().eq(LineEntity::getIdcard, userEntity.getID())
                    .eq(LineEntity::getDeptId, lineDeptEntity.getDeptId()));
            map.put("urgency", lineEntity.getUrgency());
            map.put("nownummber", lineEntities.size());
            map.put("purchaseplant", userRegistrationEntity.getPurchaseplant());
            map.put("time", userRegistrationEntity.getTime());
            map.put("model", userRegistrationEntity.getModel());
            map.put("carrythings", userRegistrationEntity.getCarrythings());
            map.put("tonnage", userRegistrationEntity.getTonnage());
            map.put("way", userRegistrationEntity.getWay());
            //排队号:排队id在当天排队表里状态为2的次序
            if (!userRegistrationEntity.getState().equals("2")) {
                map.put("order", 0);
                return map;
            } else {
                LineEntity userLine = lineDao.selectOne(new LambdaQueryWrapper<LineEntity>()
                        .eq(LineEntity::getIdcard, userEntity.getID())
                        .eq(LineEntity::getDeptId, lineDeptEntity.getDeptId())
                        .eq(LineEntity::getRegistertime, userRegistrationEntity.getTime())
                        .eq(LineEntity::getRegisterstate, 2)
                        .last("limit 1")
                );

                for (int i = 0; i < lineEntities.size(); i++) {
                    if (Objects.equals(userLine.getNumberre(), lineEntities.get(i).getNumberre())) {
                        map.put("order", i + 1);
                    }
                }
                return map;
            }
        } else {
            //其他厂不同车型分开排队
            List<LineEntity> lineEntities = lineDao.selectList(new LambdaQueryWrapper<LineEntity>()
                    .eq(LineEntity::getLineorder, lineOrder)
                    .ge(LineEntity::getRegistertime, startOfToday)
                    .lt(LineEntity::getRegistertime, startOfTomorrow)
                    .eq(LineEntity::getDeptId, lineDeptEntity.getDeptId())
                    .eq(LineEntity::getRegisterstate, 2)
                    .orderByAsc(LineEntity::getRegisterstate)
                    .orderByAsc(LineEntity::getRegistertime)
            );

            //找到该用户的排队资料
            LineEntity lineEntity = lineDao.selectOne(new LambdaQueryWrapper<LineEntity>().eq(LineEntity::getIdcard, userEntity.getID())
                    .eq(LineEntity::getDeptId, lineDeptEntity.getDeptId()));
            map.put("urgency", lineEntity.getUrgency());
            map.put("nownummber", lineEntities.size());
            map.put("purchaseplant", userRegistrationEntity.getPurchaseplant());
            map.put("time", userRegistrationEntity.getTime());
            map.put("model", userRegistrationEntity.getModel());
            map.put("carrythings", userRegistrationEntity.getCarrythings());
            map.put("tonnage", userRegistrationEntity.getTonnage());
            map.put("way", userRegistrationEntity.getWay());
            //排队号:排队id在当天排队表里状态为2的次序
            if (!userRegistrationEntity.getState().equals("2")) {
                map.put("order", 0);
                return map;
            } else {

                LineEntity userLine = lineDao.selectOne(new LambdaQueryWrapper<LineEntity>()
                        .eq(LineEntity::getLineorder, lineOrder)
                        .eq(LineEntity::getIdcard, userEntity.getID())
                        .eq(LineEntity::getDeptId, lineDeptEntity.getDeptId())
                        .eq(LineEntity::getRegistertime, userRegistrationEntity.getTime())
                        .eq(LineEntity::getRegisterstate, 2)
                        .last("limit 1")
                );

                for (int i = 0; i < lineEntities.size(); i++) {
                    if (Objects.equals(userLine.getNumberre(), lineEntities.get(i).getNumberre())) {
                        map.put("order", i + 1);
                    }
                }
                return map;
            }
        }
    }






/*
    @GetMapping("/orderInfo") //订单详情
    public R orderInfo(@RequestParam int userId, @RequestParam String purchaseplant,@RequestParam Long recordId) {
        Map<String, Object> map = new HashMap<>();
        UserEntity userEntity = userDao.findByUserId(userId);

        LineDeptEntity lineDeptEntity = lineDeptDao.selectOne(new LambdaQueryWrapper<LineDeptEntity>().eq(LineDeptEntity::getDeptName, purchaseplant));
        //司机
        map.put("driver", userEntity.getName());
        UserRegistrationEntity userRegistrationEntity = userRegistrationDao.selectOne(new LambdaQueryWrapper<UserRegistrationEntity>()
                .eq(UserRegistrationEntity::getRecordid,recordId));
        map.put("ordernumber",userRegistrationEntity.getOrderNumber());
        Integer datcherid = userRegistrationEntity.getDatcherid();
        if (datcherid == null) {
            map.put("datcher", "助手未绑定");
        }
        else {
        UserEntity datcher = userDao.findByUserId(datcherid);
        //押运人员
            map.put("datcher", datcher.getName());
        }
            //车牌号
            map.put("carnumber", userRegistrationEntity.getCarnumber());
            //当前排队车数,用户当天在排队表里的数量，状态2
            map.put("state", userRegistrationEntity.getState()); //状态
            String startOfToday = DateUtil.beginOfDay(DateUtil.date()).toString();
            String startOfTomorrow = DateUtil.beginOfDay(DateUtil.tomorrow()).toString();

            List<LineEntity> lineEntities = lineDao.selectList(new LambdaQueryWrapper<LineEntity>()
                    .ge(LineEntity::getRegistertime, startOfToday)
                    .lt(LineEntity::getRegistertime, startOfTomorrow)
                    .eq(LineEntity::getDeptId, lineDeptEntity.getDeptId())
                    .eq(LineEntity::getRegisterstate, 2)
                    .orderByAsc(LineEntity::getRegisterstate)
                    .orderByAsc(LineEntity::getRegistertime)
            );
        LineEntity lineEntity = lineDao.selectOne(new LambdaQueryWrapper<LineEntity>().eq(LineEntity::getIdcard,userEntity.getID())
                .eq(LineEntity::getDeptId,lineDeptEntity.getDeptId()));
        map.put("urgency",lineEntity.getUrgency());
            map.put("nownummber", lineEntities.size());
            //排队号:排队id在当天排队表里状态为2的次序
            if (!userRegistrationEntity.getState().equals("2")) {
                map.put("order", 0);
                return R.ok("用户未在排队中状态").put("data", map);
            } else {

                LineEntity userLine = lineDao.selectOne(new LambdaQueryWrapper<LineEntity>()
                        .eq(LineEntity::getIdcard, userEntity.getID())
                        .eq(LineEntity::getDeptId, lineDeptEntity.getDeptId())
                        .ge(LineEntity::getRegistertime, startOfToday)
                        .lt(LineEntity::getRegistertime, startOfTomorrow)
                        .eq(LineEntity::getRegisterstate, 2)
                        .last("limit 1")
                );

                for (int i = 0; i < lineEntities.size(); i++) {
                    if (Objects.equals(userLine.getNumberre(), lineEntities.get(i).getNumberre())) {
                        map.put("order", i + 1);
                    }
                }
                return R.ok().put("data", map);
            }

        }
*/


    @GetMapping("/deptNames") //厂区名字
    public Response getDepNames() {
        List<String> data = linedeptService.getDepNames();
        return new Response(0, "Success", data);
    }


    @PostMapping("/scancode") //驻厂扫码确认
    public Response scancode(@RequestParam int idrp, @RequestParam int userId,@RequestParam String time) {
        // 从数据库中获取LineEntity
        UserEntity userEntity = userDao.findByUserId(userId);
        LineEntity lineEntity = lineDao.selectOne(new LambdaQueryWrapper<LineEntity>()
                .eq(LineEntity::getIdcard,userEntity.getID())
                .eq(LineEntity::getRegistertime,time));
        if (lineEntity == null) {
            return new Response(404, "未报到", null);
        }
        if(!lineEntity.getRegisterstate().equals("3")){
            return new Response(404, "非已报到状态，扫码确认失败", null);
        }
        // 更新LineEntity的registerstate
        lineEntity.setRegisterstate("2");
        lineEntity.setIdrp(idrp);
        lineDao.updateById(lineEntity);

        // 从数据库中获取UserRegistrationEntity
        UserRegistrationEntity userRegistrationEntity = userRegistrationDao.selectOne(new LambdaQueryWrapper<UserRegistrationEntity>()
                .eq(UserRegistrationEntity::getDriverid,userId)
                .eq(UserRegistrationEntity::getTime,time));
        if (userRegistrationEntity == null) {
            return new Response(404, "未车检", null);
        }
        if(!userRegistrationEntity.getState().equals("3")){
            return new Response(404, "非已报到状态，扫码确认失败", null);
        }
        // 更新UserRegistrationEntity的state
        userRegistrationEntity.setState("2");
        userRegistrationEntity.setReid(idrp);
        userRegistrationDao.updateById(userRegistrationEntity);

        return new Response(0, "Success", null);
    }

    @PostMapping("/callnum") //驻厂叫号
    public Response callnum(@RequestParam String ID,@RequestParam String time) {
        // 从数据库中获取LineEntity
        UserEntity userEntity = userDao.findByID(ID);
        LineEntity lineEntity = lineDao.selectOne(new LambdaQueryWrapper<LineEntity>()
                .eq(LineEntity::getIdcard, userEntity.getID())
                .eq(LineEntity::getRegistertime, time));

        String startOfToday = DateUtil.beginOfDay(DateUtil.date()).toString();
        String startOfTomorrow = DateUtil.beginOfDay(DateUtil.tomorrow()).toString();
        // 从数据库中获取UserRegistrationEntity
        UserRegistrationEntity userRegistrationEntity = userRegistrationDao.selectOne(new LambdaQueryWrapper<UserRegistrationEntity>()
                .eq(UserRegistrationEntity::getDriverid, userEntity.getUser_id())
                .eq(UserRegistrationEntity::getTime, time));
        if (userRegistrationEntity == null) {
            return new Response(404, "未车检", null);
        }

        if (lineEntity == null) {
            return new Response(404, "未报到", null);
        }

        List<LineEntity> lineEntities = lineDao.selectList(new LambdaQueryWrapper<LineEntity>()
                .ge(LineEntity::getRegistertime, startOfToday)
                .lt(LineEntity::getRegistertime, startOfTomorrow)
                .eq(LineEntity::getDeptId, lineEntity.getDeptId())
                .eq(LineEntity::getRegisterstate, 2)
                .orderByAsc(LineEntity::getRegistertime)
        );//今日排队中的人数
        List<LineEntity> callEntities = lineDao.selectList(new LambdaQueryWrapper<LineEntity>()
                .ge(LineEntity::getRegistertime, startOfToday)
                .lt(LineEntity::getRegistertime, startOfTomorrow)
                .eq(LineEntity::getDeptId, lineEntity.getDeptId())
                .eq(LineEntity::getRegisterstate, 1)
        );//今日该厂已经叫号的人数
        int jizhuangx = 0, pingbanche = 0;
        for (LineEntity entity : callEntities) {
            UserEntity user = userDao.findByID(entity.getIdcard());
            UserRegistrationEntity regis = userRegistrationDao.selectOne(new LambdaQueryWrapper<UserRegistrationEntity>()
                    .eq(UserRegistrationEntity::getDriverid, user.getUser_id())
                    .eq(UserRegistrationEntity::getTime, entity.getRegistertime()));
            if (regis.getModel().equals("厢式X")) jizhuangx++;
            else if (regis.getModel().equals("平板P")) pingbanche++;
        }//遍历该厂已叫号，从中获取各车型被叫号的数量
        int deptId = lineEntity.getDeptId();


        if (deptId == 5 || deptId == 6) {
            if (callEntities.size() == 8) {
                return new Response(404, "当前位置已满", null);
            }
        } else if (deptId == 13) {
            if (callEntities.size() == 4) {
                return new Response(404, "当前位置已满", null);
            }
        } else if (deptId == 8) {
            if (userRegistrationEntity.getModel().equals("厢式X")) {
                if (jizhuangx >= 2) return new Response(404, "当前厢式X位置已满", null);
            } else if (userRegistrationEntity.getModel().equals("平板P")) {
                if (pingbanche >= 2) return new Response(404, "当前平板P位置已满", null);
            } else if (deptId == 7) {
                if (userRegistrationEntity.getModel().equals("厢式X")) {
                    if (jizhuangx >= 3) return new Response(404, "当前厢式X位置已满", null);
                } else if (userRegistrationEntity.getModel().equals("平板P")) {
                    if (pingbanche >= 2) return new Response(404, "当前平板P位置已满", null);
                }
            } else if (deptId == 12) {
                if (userRegistrationEntity.getModel().equals("厢式X")) {
                    if (jizhuangx >= 2) return new Response(404, "当前厢式X位置已满", null);
                } else if (userRegistrationEntity.getModel().equals("平板P")) {
                    if (pingbanche >= 3) return new Response(404, "当前平板P位置已满", null);
                }
            } else if (deptId == 11) {
                if (userRegistrationEntity.getModel().equals("厢式X")) {
                    if (jizhuangx >= 3) return new Response(404, "当前厢式X位置已满", null);
                } else if (userRegistrationEntity.getModel().equals("平板P")) {
                    if (pingbanche >= 3) return new Response(404, "当前平板P位置已满", null);
                }
            } else if (deptId == 9) {
                if (userRegistrationEntity.getModel().equals("厢式X")) {
                    if (jizhuangx >= 3) return new Response(404, "当前厢式X位置已满", null);
                } else if (userRegistrationEntity.getModel().equals("平板P")) {
                    if (pingbanche >= 5) return new Response(404, "当前平板P位置已满", null);
                }
            } else if (deptId == 10) {
                if (userRegistrationEntity.getModel().equals("厢式X")) {
                    if (jizhuangx >= 2) return new Response(404, "当前厢式X位置已满", null);
                } else if (userRegistrationEntity.getModel().equals("平板P")) {
                    if (pingbanche >= 1) return new Response(404, "当前平板P位置已满", null);
                }
            }
        }
            int order = 0;
            for (int i = 0; i < lineEntities.size(); i++) {
                if (Objects.equals(lineEntity.getNumberre(), lineEntities.get(i).getNumberre())) {
                    order = i + 1;
                }
            }
            // 更新LineEntity的registerstate,只能在前5个
            if (order <= 5 && order >= 1) {
                lineEntity.setRegisterstate("1");
                lineDao.updateById(lineEntity);
            } else {
                return new Response(404, "只许在前5个顺序中叫号", null);
            }

            // 更新UserRegistrationEntity的state
            userRegistrationEntity.setState("1");
            userRegistrationDao.updateById(userRegistrationEntity);
        /**
         * 叫号成功了给微信发送模版消息
         * 小明叫号成功了
         */
        try {
            String accessToken = wechatTokenService.getToken();
            WeChatUtil.sendMsg("小明叫号成功了",accessToken,userEntity.getOpenId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return new Response(0, "Success", null);
        }

    @PostMapping("/check") //驻厂查看
    public Response check(@RequestParam String ID,@RequestParam String time) {
        // 从数据库中获取LineEntity
        UserEntity userEntity = userDao.findByID(ID);
        LineEntity lineEntity = lineDao.selectOne(new LambdaQueryWrapper<LineEntity>()
                .eq(LineEntity::getIdcard,userEntity.getID())
                .eq(LineEntity::getRegistertime,time));
        if (lineEntity == null) {
            return new Response(404, "未报到", null);
        }

        // 更新LineEntity的registerstate
        lineEntity.setRegisterstate("3");
        lineDao.updateById(lineEntity);

        // 从数据库中获取UserRegistrationEntity
        UserRegistrationEntity userRegistrationEntity = userRegistrationDao.selectOne(new LambdaQueryWrapper<UserRegistrationEntity>()
                .eq(UserRegistrationEntity::getDriverid,userEntity.getUser_id())
                .eq(UserRegistrationEntity::getTime,time));
        if (userRegistrationEntity == null) {
            return new Response(404, "未车检", null);
        }

        // 更新UserRegistrationEntity的state
        userRegistrationEntity.setState("3");
        userRegistrationDao.updateById(userRegistrationEntity);

        return new Response(0, "Success", null);
    }

    @PostMapping("/chargeback") //退单
    public Response chargeback(@RequestParam String ID,@RequestParam String time) {
        // 从数据库中获取LineEntity
        UserEntity userEntity = userDao.findByID(ID);
        LineEntity lineEntity = lineDao.selectOne(new LambdaQueryWrapper<LineEntity>()
                .eq(LineEntity::getIdcard,userEntity.getID())
                .eq(LineEntity::getRegistertime,time));
        if (lineEntity == null) {
            return new Response(404, "未报到", null);
        }

        // 更新LineEntity的registerstate
        lineEntity.setRegisterstate("6");
        lineDao.updateById(lineEntity);

        // 从数据库中获取UserRegistrationEntity
        UserRegistrationEntity userRegistrationEntity = userRegistrationDao.selectOne(new LambdaQueryWrapper<UserRegistrationEntity>()
                .eq(UserRegistrationEntity::getDriverid,userEntity.getUser_id())
                .eq(UserRegistrationEntity::getTime,time));
        if (userRegistrationEntity == null) {
            return new Response(404, "未车检", null);
        }

        // 更新UserRegistrationEntity的state
        userRegistrationEntity.setState("6");
        userRegistrationDao.updateById(userRegistrationEntity);

        return new Response(0, "Success", null);
    }

    @PostMapping("/quitfactory") //离厂
    public Response quitfactory(@RequestParam String ID,@RequestParam String time) {
        // 从数据库中获取LineEntity
        UserEntity userEntity = userDao.findByID(ID);
        LineEntity lineEntity = lineDao.selectOne(new LambdaQueryWrapper<LineEntity>()
                .eq(LineEntity::getIdcard,userEntity.getID())
                .eq(LineEntity::getRegistertime,time));
        if (lineEntity == null) {
            return new Response(404, "未报到", null);
        }

        // 更新LineEntity的registerstate
        lineEntity.setRegisterstate("5");
        lineDao.updateById(lineEntity);

        // 从数据库中获取UserRegistrationEntity
        UserRegistrationEntity userRegistrationEntity = userRegistrationDao.selectOne(new LambdaQueryWrapper<UserRegistrationEntity>()
                .eq(UserRegistrationEntity::getDriverid,userEntity.getUser_id())
                .eq(UserRegistrationEntity::getTime,time));
        if (userRegistrationEntity == null) {
            return new Response(404, "未车检", null);
        }

        // 更新UserRegistrationEntity的state
        userRegistrationEntity.setState("5");
        userRegistrationDao.updateById(userRegistrationEntity);

        return new Response(0, "Success", null);
    }



}

